package com.mzj.eagle.jobs.config.mq;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;


@Configuration
public class RabbitMQConfig {
	
	// RabbitMQ的配置信息
	@Value("${spring.rabbitmq.host}")
	private String springRabbitmqHost;
	@Value("${spring.rabbitmq.port}")
	private Integer springRabbitmqPort;
	@Value("${spring.rabbitmq.username}")
	private String springRabbitmqUsername;
	@Value("${spring.rabbitmq.password}")
	private String springRabbitmqPassword;
	@Value("${spring.rabbitmq.virtualHost}")
	private String springRabbitmqVirtualHost;
	
	@Bean("connectionFactory")
	@Primary
	public ConnectionFactory connectionFactory() {
		CachingConnectionFactory connectionFactory = new CachingConnectionFactory(springRabbitmqHost, springRabbitmqPort);

		connectionFactory.setUsername(springRabbitmqUsername);
		connectionFactory.setPassword(springRabbitmqPassword);
		connectionFactory.setVirtualHost(springRabbitmqVirtualHost);
		connectionFactory.setPublisherConfirms(true); 
		return connectionFactory;
	}

	@Bean
	@Primary
	public AmqpAdmin amqpAdmin() {
		final RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory());
	    rabbitAdmin.afterPropertiesSet();
	    return rabbitAdmin;
	}

	@Bean("rabbitTemplate")
	@Primary
	public RabbitTemplate rabbitTemplate() {
		RabbitTemplate template = new RabbitTemplate(connectionFactory());
		return template;
	}
}